from django.contrib import admin
from certificate_manager.models import CollectCate, Cate
from datetime import date

from django.utils.translation import gettext_lazy as _

class ValidFilter(admin.SimpleListFilter):
        title = _('是否有效')

        parameter_name = 'is_valid'

        def lookups(self, request, model_admin):
                return [(True, '有效'), (False, '无效')]

        def queryset(self, request, queryset):
                now = date.today()
                if self.value() == 'True':
                        return queryset.filter(start_date__lte=now, end_date__gte=now)
                elif self.value() == 'False':
                        return queryset.exclude(start_date__lte=now, end_date__gte=now)

@admin.register(CollectCate)
class CollectCateAdmin(admin.ModelAdmin):
        fields = ['cate', 'start_date', 'end_date']
        list_display = ('cate', 'start_date', 'end_date', 'is_valid', 'collected_count')
        list_filter = (ValidFilter, )

        @admin.display(boolean=True)
        def is_valid(self, ccate):
                return ccate.start_date <= date.today() <= ccate.end_date

        @admin.display()
        def collected_count(self, ccate):
                return ccate.cert_set.count()
                

        def get_form(self, request, obj=None, **kwargs):
                form = super().get_form(request, obj, **kwargs)
                print(form.base_fields)
                form.base_fields['cate'].queryset = Cate.objects.filter(collecable=True)
                return form

        

